package com.ruoyi.web.controller.stock;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.ruoyi.client.domain.*;
import com.ruoyi.client.service.*;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.AlipayConts;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/stock/klinegraph")
public class KlineGraphController extends BaseController {
    @Autowired
    ICommissionService iCommissionService;
    @Autowired
    ICommissionNoService iCommissionNoService;
    @Autowired
    ICommissionYesService iCommissionYesService;
    @Autowired
    IPayPlanService iPayPlanService;
    @Autowired
    ITbStockVoService iTbStockVoService;
    @Autowired
    IMyAccountService iMyAccountService;
    @Autowired
    ISysBuyService iSysBuyService;
    @Autowired
    ISysSellService iSysSellService;
    @Autowired
    ISysHoldStockService iSysHoldStockService;

    //获取某个股票的k线图
    @PostMapping("lineList")
    public AjaxResult lineList(String symbol){
        List<KlineGraph> klineGraphs = klineGraphList(symbol);
        return success(klineGraphs);
    }
    //解析k线图
    public List<KlineGraph> klineGraphList(String symbol){
        String url="https://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sh600519&scale=240&ma=no&datalen=10";
        HashMap<String, Object> map = new HashMap<>();
        map.put("symbol",symbol);
        map.put("scale",240);
        map.put("ma","no");
        map.put("datalen",1023);
        String result = HttpUtil.get(url,map);
        //获取result里面的数据存入数据库
        //System.out.println(result);
        ArrayList<KlineGraph> klineGraphs = new ArrayList<>();
        ArrayList<JSONObject> jsonObjects = new ArrayList<>();
        JSONArray objects = new JSONArray(result);
        for (int i = 0; i < objects.size(); i++) {
            jsonObjects.add(objects.getJSONObject(i));
        }
        for (JSONObject jsonObject : jsonObjects) {
            KlineGraph klineGraph = new KlineGraph();
            klineGraph.setHigh(jsonObject.getStr("high"));
            klineGraph.setLow(jsonObject.getStr("low"));
            klineGraph.setOpen(jsonObject.getStr("open"));
            klineGraph.setClose(jsonObject.getStr("close"));
            klineGraph.setVolume(jsonObject.getStr("volume"));
            klineGraph.setDay(jsonObject.getStr("day"));
            klineGraphs.add(klineGraph);
        }
        return klineGraphs;
    }

    /**
     * 获取当前登录的账户
     */
    @PreAuthorize("@ss.hasPermi('stock:klinegraph:account')")
    @PostMapping("account")
    public AjaxResult account(){
        String name = SecurityUtils.getUsername();
        //String name="admin";
        MyAccount myAccount=iMyAccountService.selectMyAccount(name);

        return success(myAccount);
    }

    //买入列表
    @PostMapping("buyList")
    public AjaxResult buyList(String symbol,String trade){
        System.out.println(symbol);
        System.out.println(trade);
        double num=Double.parseDouble(trade);
        num=num+0.01;
        List<SysBuy> sysBuys = iSysBuyService.sysBuyList(symbol);
        if(sysBuys.size()<=0){
            for (int i = 1; i <=5; i++) {
                SysBuy sysBuy = new SysBuy();
                num -=0.01;
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                String format = decimalFormat.format(num);
                System.err.println(format);
                sysBuy.setName("买"+i);
                sysBuy.setBuyPrice(format);
                sysBuy.setSymbol(symbol);
                Random random = new Random();
                sysBuy.setHands(String.valueOf(random.nextInt(1001)));
                iSysBuyService.add(sysBuy);
            }
            return success(iSysBuyService.sysBuyList(symbol));
        }
        return success(sysBuys);
    }

    //卖出列表
    @PostMapping("sellList")
    public AjaxResult sellList(String symbol,String trade){
        System.out.println(symbol);
        System.out.println(trade);
        double num=Double.parseDouble(trade);
        List<SysSell> sysBuys = iSysSellService.sysSellList(symbol);
        if(sysBuys.size()<=0){
            for(int i = 1; i <= 5; i++) {
                SysSell sysSell = new SysSell();
                num+=0.01;
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                String format = decimalFormat.format(num);
                System.err.println(format);
                sysSell.setSellPrice(format);
                Random random = new Random();
                sysSell.setHands(String.valueOf(random.nextInt(1001)));
                sysSell.setName("卖"+i);
                sysSell.setSymbol(symbol);
                iSysSellService.add(sysSell);
            }
            return success(iSysSellService.sysSellList(symbol));
        }
        return AjaxResult.success(sysBuys);
    }
    @Anonymous
    @GetMapping("toPay")
    public String toPay(String name,BigDecimal addPrice) throws AlipayApiException {
        MyAccount myAccount = iMyAccountService.selectMyAccount(name);
        myAccount.setOutTradeNo(IdUtil.getSnowflake().nextIdStr());
        myAccount.setAddPrice(addPrice);
        iMyAccountService.updateByOutTradeNo(myAccount);

        System.out.println("pppp==="+myAccount.getOutTradeNo());
        AlipayClient alipayClient = AlipayConts.ALIPAY_CLIENT;
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(AlipayConts.NOTIFY_URL);
//同步跳转地址，仅支持http/https
        request.setReturnUrl(AlipayConts.RETURN_URL);
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", myAccount.getOutTradeNo());
//支付金额，最小值0.01元
        bizContent.put("total_amount", addPrice);
//订单标题，不可使用特殊符号
        bizContent.put("subject", "充值");
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

/******可选参数******/
//bizContent.put("time_expire", "2022-08-01 22:00:00");
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"POST");
// 如果需要返回GET请求，请使用
// AlipayTradePagePayResponse response = alipayClient.pageExecute(request,"GET");
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if(response.isSuccess()){
            System.out.println("调用成功 :body="+response.getBody());
            return response.getBody();
        } else {
            System.out.println("调用失败");
            return "error";
        }

    }
    //充值
    @Anonymous
    @RequestMapping("alipayCallback")
    public void alipayCallback(HttpServletRequest request) throws AlipayApiException {
        System.err.println("我是小妹！！！！！");
        final Map<String, String> paramMap = ServletUtil.getParamMap(request);
        boolean b = AlipaySignature.rsaCheckV1(paramMap, AlipayConts.ALIPAY_PUBLIC_KEY, AlipayConts.CHARSET, AlipayConts.SIGN_TYPE);
        final String tradeStatus = paramMap.get("trade_status");
        if(b&& StrUtil.equalsIgnoreCase(tradeStatus,AlipayConts.TRADE_SUCCESS)){
            final String outTradeNo = paramMap.get("out_trade_no");
            MyAccount myAccount = iMyAccountService.selectMyAccountByOutTradeNo(outTradeNo);
            final BigDecimal addPrice = myAccount.getAddPrice();
            System.out.println(addPrice);
            BigDecimal newBalance = myAccount.getBalance().add(myAccount.getAddPrice());
            System.err.println(newBalance);
            iMyAccountService.updateById(newBalance,myAccount.getId());
            System.err.println(myAccount);
        }
    }
    @PostMapping("getNameBySymbol")
    public AjaxResult getNameBySymbol(String symbol){
        TbStockVo tbStockVo= iTbStockVoService.getNameBySymbol(symbol);
        return success(tbStockVo);
    }
    /**
     * 买入
     */
    @PostMapping("getBuying")
    public AjaxResult getBuying(TbStockVoTest tbStockVoTest){
        String username = SecurityUtils.getUsername();
        MyAccount myAccount = iMyAccountService.selectMyAccount(username);
        //全部委托
        //先判断委托表中是否存在该笔交易
        Commission commission=iCommissionService.getCommissionBySymbolAndPrice(tbStockVoTest.getSymbol(),tbStockVoTest.getBuyPrice(),myAccount.getId());
        if (commission==null){
            commission=new Commission();
            commission.setSymbol(tbStockVoTest.getSymbol());
            commission.setCommissionPrice(new BigDecimal(tbStockVoTest.getBuyPrice()));
            commission.setNum(tbStockVoTest.getNum() / 100);
            commission.setAccountId(myAccount.getId());
            commission.setState(1);
            iCommissionService.add(commission);
        }else{
            //如果存在 就修改数量
            commission.setNum(commission.getNum()+tbStockVoTest.getNum()/100);
            iCommissionService.updateNumById(commission.getNum(),commission.getId());
        }


        int dbHands=0;
        System.err.println(tbStockVoTest);
        //一股的价格
        BigDecimal bigDecimal = new BigDecimal(tbStockVoTest.getBuyPrice());
        System.err.println(bigDecimal);
        //总股的价格
        bigDecimal=bigDecimal.multiply(new BigDecimal(tbStockVoTest.getNum()));
        System.out.println(bigDecimal);

        BigDecimal balance = myAccount.getBalance();
        //如果bigDecimal比balance大就返回余额不足
        if(bigDecimal.compareTo(balance)>=0){
            return AjaxResult.success("201","余额不足");
        }
        //从账户减去买入股票的钱

        iMyAccountService.updateById(balance.subtract(bigDecimal),myAccount.getId());
        //卖出的列表
        List<SysSell> sysSells = iSysSellService.sysSellListAll(tbStockVoTest.getSymbol());
        //买入的价格大于卖出的价格优先成交低于买入价格卖出的最低价
        List<SysSell> eligibleSells = sysSells.stream()
                .filter(sell -> new BigDecimal(sell.getSellPrice()).compareTo(new BigDecimal(tbStockVoTest.getBuyPrice())) <=0)
                .sorted(Comparator.comparing(sell -> new BigDecimal(sell.getSellPrice())))
                .collect(Collectors.toList());

        System.err.println(eligibleSells);

        //如果存在符合条件的卖出订单
        if (!eligibleSells.isEmpty()) {
            //选择价格最低的卖出订单进行成交
            BigDecimal lowestSellPrice = new BigDecimal(eligibleSells.get(0).getSellPrice());
            //执行成交操作，这里可以根据实际需求进行处理
            System.out.println("买入价格大于卖出价格，成交价格为低于买入价格卖出股票的最低价：" + lowestSellPrice);

            //计算低于买入价格卖出股票的最低价的股票的剩余手数
            int remainingHands = eligibleSells.stream()
                    .mapToInt(sell -> Integer.parseInt(sell.getHands()))
                    .sum();
            System.out.println("低于买入价格卖出的所有手数：" + remainingHands);

            //判断要买入的手数是否低于剩余手数
            int targetHands = tbStockVoTest.getNum() / 100;
            if (targetHands <= remainingHands) {

                //
                CommissionYes commissionYes=iCommissionYesService.getCommissionBySymbolAndPrice(tbStockVoTest.getSymbol(),tbStockVoTest.getBuyPrice(),myAccount.getId());
                if (commissionYes==null){
                    commissionYes=new CommissionYes();
                    commissionYes.setSymbol(tbStockVoTest.getSymbol());
                    commissionYes.setCommissionPrice(new BigDecimal(tbStockVoTest.getBuyPrice()));
                    commissionYes.setNum(targetHands);
                    commissionYes.setAccountId(myAccount.getId());
                    commissionYes.setState(1);
                    iCommissionYesService.add(commissionYes);
                }else{
                    //如果存在 就修改数量
                    commissionYes.setNum(commission.getNum()+targetHands);
                    iCommissionYesService.updateNumById(commissionYes.getNum(),commissionYes.getId());
                }



                //如果足够，直接返回 打印出从哪条数据减了手数
                System.out.println("买入手数小于等于剩余手数，无需调整");
                for (SysSell sell : eligibleSells) {
                    System.err.println("哈哈-----哈哈=="+sell);
                    int handsToReduce = Math.min(Integer.parseInt(sell.getHands()), targetHands);
                    System.out.println("减少了 " + handsToReduce + " 手，来自订单：" + sell.getName());
                    dbHands+=handsToReduce;
                    //修改卖出的手数
                    SysSell sysSell = iSysSellService.selectSysSellById(sell.getId());
                    sysSell.setHands(String.valueOf(Integer.parseInt(sell.getHands()) - handsToReduce));
                    iSysSellService.updateHandsById(sysSell);
                    //判断当前账户（sysHoldStock）是否持有该股票 如果持有就在原有的基础上加上handsToReduce
                    SysHoldStock sysHoldStock=iSysHoldStockService.getStockBySymbol(sell.getSymbol());
                    if(sysHoldStock==null){
                        sysHoldStock=new SysHoldStock();
                        sysHoldStock.setNum(handsToReduce);
                        sysHoldStock.setSymbol(sell.getSymbol());
                        Integer userId = Math.toIntExact(SecurityUtils.getUserId());
                        sysHoldStock.setAccountId(userId);
                        sysHoldStock.setCurrentRate(new BigDecimal(sell.getSellPrice()));
                        iSysHoldStockService.add(sysHoldStock);
                    }
                    else{
                        //如果sysHoldStock存在，就在原有num的基础上加上handsToReduce
                        sysHoldStock.setNum(sysHoldStock.getNum()+handsToReduce);
                        iSysHoldStockService.updateNumById(sysHoldStock.getNum(),sell.getSymbol());
                    }
                    targetHands -= handsToReduce;
                    if (targetHands == 0) {
                        break;
                    }
                }





            } else {
                //手数不够，需要进行调整
                int deficit = targetHands - remainingHands;



                CommissionYes commissionYes=iCommissionYesService.getCommissionBySymbolAndPrice(tbStockVoTest.getSymbol(),tbStockVoTest.getBuyPrice(),myAccount.getId());
                if (commissionYes==null){
                    commissionYes=new CommissionYes();
                    commissionYes.setSymbol(tbStockVoTest.getSymbol());
                    commissionYes.setCommissionPrice(new BigDecimal(tbStockVoTest.getBuyPrice()));
                    commissionYes.setNum(remainingHands);
                    commissionYes.setAccountId(myAccount.getId());
                    commissionYes.setState(1);
                    iCommissionYesService.add(commissionYes);
                }else{
                    //如果存在 就修改数量
                    commissionYes.setNum(commissionYes.getNum()+tbStockVoTest.getNum()/100);
                    iCommissionYesService.updateNumById(commissionYes.getNum(),commissionYes.getId());
                }


                List<SysSell> equalSellss = sysSells.stream()
                        .filter(sell -> new BigDecimal(sell.getSellPrice()).compareTo(new BigDecimal(tbStockVoTest.getBuyPrice())) < 0)
                        .collect(Collectors.toList());
                //可以根据实际需求进行进一步处理，比如调整买入手数或者返回错误信息
                for (SysSell sell : equalSellss) {
                    int handsToReduce = Math.min(Integer.parseInt(sell.getHands()), deficit);
                    System.out.println("减少了 " + handsToReduce + " 手，来自订单：" + sell.getName());
                    //同步到数据库 给卖出股票的手数进行减减
                    SysSell sysSell=iSysSellService.selectSysSellById(sell.getId());
                    sysSell.setHands(String.valueOf(Integer.parseInt(sysSell.getHands())-handsToReduce));
                    iSysSellService.updateHandsById(sysSell);
                    //判断当前账户（sysHoldStock）是否持有该股票 如果持有就在原有的基础上加上handsToReduce
                    SysHoldStock sysHoldStock=iSysHoldStockService.getStockBySymbol(sell.getSymbol());
                    if(sysHoldStock==null){
                        sysHoldStock=new SysHoldStock();
                        sysHoldStock.setNum(handsToReduce);
                        sysHoldStock.setSymbol(sell.getSymbol());
                        Integer userId = Math.toIntExact(SecurityUtils.getUserId());
                        sysHoldStock.setCurrentRate(new BigDecimal(sell.getSellPrice()));
                        sysHoldStock.setAccountId(userId);
                        iSysHoldStockService.add(sysHoldStock);
                    }
                    else{
                        //如果sysHoldStock存在，就在原有num的基础上加上handsToReduce
                        sysHoldStock.setNum(sysHoldStock.getNum()+handsToReduce);
                        iSysHoldStockService.updateNumById(sysHoldStock.getNum(), sell.getSymbol());
                    }
                    targetHands -= handsToReduce;
                    if (targetHands == deficit) {
                        break;
                    }
                }


                List<SysSell> equalSells = sysSells.stream()
                        .filter(sell -> new BigDecimal(sell.getSellPrice()).compareTo(new BigDecimal(tbStockVoTest.getBuyPrice())) == 0)
                        .collect(Collectors.toList());

                if (!equalSells.isEmpty()) {
                    for (SysSell sell : equalSells) {
                        int handsToReduce = Math.min(Integer.parseInt(sell.getHands()), targetHands);
                        System.out.println("买入价格等于卖出价格的股票减少了 " + handsToReduce + " 手，来自订单：" + sell.getName());
                        //相等的时候做处理
                        SysSell sysSell=iSysSellService.selectSysSellById(sell.getId());
                        sysSell.setHands(String.valueOf(Integer.parseInt(sysSell.getHands())-handsToReduce));
                        iSysSellService.updateHandsById(sysSell);
                        //判断当前账户（sysHoldStock）是否持有该股票 如果持有就在原有的基础上加上handsToReduce
                        SysHoldStock sysHoldStock=iSysHoldStockService.getStockBySymbol(sell.getSymbol());
                        if(sysHoldStock==null){
                            sysHoldStock=new SysHoldStock();
                            sysHoldStock.setNum(handsToReduce);
                            sysHoldStock.setSymbol(sell.getSymbol());
                            Integer userId = Math.toIntExact(SecurityUtils.getUserId());
                            sysHoldStock.setAccountId(userId);
                            sysHoldStock.setCurrentRate(new BigDecimal(sell.getSellPrice()));
                            iSysHoldStockService.add(sysHoldStock);
                        }
                        else{
                            //如果sysHoldStock存在，就在原有num的基础上加上handsToReduce
                            sysHoldStock.setNum(sysHoldStock.getNum()+handsToReduce);
                            iSysHoldStockService.updateNumById(sysHoldStock.getNum(), sell.getSymbol());
                        }
                        //判断sysBuy里是否有tbStockVoTest.getBuyPrice()价格的订单
                        SysBuy sysBuy=iSysBuyService.getSysBuyByPrice(tbStockVoTest.getSymbol(),tbStockVoTest.getBuyPrice());
                        if(sysBuy==null){
                            sysBuy=new SysBuy();
                            sysBuy.setName("买"+UUID.randomUUID());
                            sysBuy.setBuyPrice(tbStockVoTest.getBuyPrice());
                            sysBuy.setSymbol(tbStockVoTest.getSymbol());
                            sysBuy.setHands(String.valueOf(handsToReduce));
                            iSysBuyService.add(sysBuy);
                        }
                        else{
                            //如果存在
                            sysBuy.setHands(String.valueOf(Integer.parseInt(sysBuy.getHands())+handsToReduce));
                            iSysBuyService.updateHandsByIds(sysBuy.getId(),sysBuy.getHands());
                        }
                        targetHands -= handsToReduce;
                        if (targetHands == 0) {
                            break;
                        }
                    }
                }

                if (deficit > 0) {
                    System.out.println("还需要买入 " + deficit + " 手才能满足条件");
                    CommissionNo commissionNo=iCommissionNoService.getCommissionBySymbolAndPrice(tbStockVoTest.getSymbol(),tbStockVoTest.getBuyPrice(),myAccount.getId());
                    if (commissionNo==null){
                        commissionNo=new CommissionNo();
                        commissionNo.setSymbol(tbStockVoTest.getSymbol());
                        commissionNo.setCommissionPrice(new BigDecimal(tbStockVoTest.getBuyPrice()));
                        commissionNo.setNum(deficit);
                        commissionNo.setAccountId(myAccount.getId());
                        commissionNo.setState(1);
                        iCommissionNoService.add(commissionNo);
                    }else{
                        //如果存在 就修改数量
                        commissionNo.setNum(commissionNo.getNum()+deficit);
                        iCommissionNoService.updateNumById(commissionNo.getNum(),commissionNo.getId());
                    }

                    SysBuy sysBuy=iSysBuyService.getSysBuyByPrice(tbStockVoTest.getSymbol(),tbStockVoTest.getBuyPrice());
                    if(sysBuy==null){
                        sysBuy=new SysBuy();
                        sysBuy.setName("买"+UUID.randomUUID());
                        sysBuy.setBuyPrice(tbStockVoTest.getBuyPrice());
                        sysBuy.setSymbol(tbStockVoTest.getSymbol());
                        sysBuy.setHands(String.valueOf(deficit));
                        iSysBuyService.add(sysBuy);
                    }
                    else{
                        //如果存在
                        sysBuy.setHands(String.valueOf(Integer.parseInt(sysBuy.getHands())+deficit));
                        iSysBuyService.updateHandsByIds(sysBuy.getId(),sysBuy.getHands());
                    }
                }
            }
            return AjaxResult.success();
        } else {
            //买入价格等于卖出价格的逻辑
            int targetHands = tbStockVoTest.getNum() / 100;
            System.err.println("要买入的价格为："+new BigDecimal(tbStockVoTest.getBuyPrice())+",要买"+targetHands+"手"+"暂时没有条件可以满足");
            return AjaxResult.success();
        }
    }
    /*卖出*/
    @PostMapping("getSelling")
    public AjaxResult getSelling(TbStockVoTest tbStockVoTest){
        System.out.println("前端传过来的数据"+tbStockVoTest);
        final String username = SecurityUtils.getUsername();//获取当前登录人
        final MyAccount myAccount = iMyAccountService.selectMyAccount(username);//获取当前账号
        //判断委托表中是否存在该委托任务
        Commission commission=iCommissionService.getCommissionBySymbolAndPriceSell(tbStockVoTest.getSymbol(),tbStockVoTest.getSellPrice(),myAccount.getId());
        System.err.println(commission);
        if (commission==null){
            commission=new Commission();
            commission.setSymbol(tbStockVoTest.getSymbol());
            commission.setCommissionPrice(new BigDecimal(tbStockVoTest.getSellPrice()));
            commission.setNum(tbStockVoTest.getNum() / 100);
            commission.setAccountId(myAccount.getId());
            commission.setState(2);
            iCommissionService.add(commission);
        }else{
            //如果存在 就修改数量
            commission.setNum(commission.getNum()+tbStockVoTest.getNum()/100);
            iCommissionService.updateNumById(commission.getNum(),commission.getId());
        }


        String sellPrice = tbStockVoTest.getSellPrice();
        //卖出的价格
        BigDecimal bigDecimal = new BigDecimal(sellPrice);
        System.err.println("卖出的价格为："+bigDecimal);
        final Long userId = SecurityUtils.getUserId();//获取当前登录人的userId

        BigDecimal bigDecimal1 = new BigDecimal(sellPrice);
        bigDecimal1=bigDecimal1.multiply(new BigDecimal(tbStockVoTest.getNum()));

        SysHoldStock sysHoldStock=iSysHoldStockService.getStockBySymbolAndId(tbStockVoTest.getSymbol(),myAccount.getId());
        //判断是否持有该股票
        if(sysHoldStock==null){
            return AjaxResult.error("该股票未持有");
        }
        iMyAccountService.updateById(myAccount.getBalance().add(bigDecimal1), Math.toIntExact(userId));
        //买入股票的列表
        List<SysBuy> sysBuys = iSysBuyService.sysBuyListAll(tbStockVoTest.getSymbol());
        //过滤出买入价格高于或等于我们卖出价格的买入订单，并按照买入价格降序排序

        List<SysBuy> eligibleBuys = sysBuys.stream()
                .filter(buy -> new BigDecimal(buy.getBuyPrice()).compareTo(bigDecimal) >= 0)
                .sorted(Comparator.comparing(buy -> new BigDecimal(buy.getBuyPrice()),Collections.reverseOrder()))
                .collect(Collectors.toList());
        System.err.println(eligibleBuys);
        final Integer num = tbStockVoTest.getNum();

        if(!eligibleBuys.isEmpty()){
            //卖出的手数
            int hands=num/100;
            int remainingHands = eligibleBuys.stream()
                    .mapToInt(sell -> Integer.parseInt(sell.getHands()))
                    .sum();
            System.out.println(remainingHands);
            if(remainingHands>=hands){

                //如果剩余的买入手数大于卖出的手数
                CommissionYes commissionYes=iCommissionYesService.getCommissionBySymbolAndPriceSell(tbStockVoTest.getSymbol(),tbStockVoTest.getSellPrice(),myAccount.getId());
                if (commissionYes==null){
                    commissionYes=new CommissionYes();
                    commissionYes.setSymbol(tbStockVoTest.getSymbol());
                    commissionYes.setCommissionPrice(new BigDecimal(tbStockVoTest.getSellPrice()));
                    commissionYes.setNum(hands);
                    commissionYes.setAccountId(myAccount.getId());
                    commissionYes.setState(2);
                    iCommissionYesService.add(commissionYes);
                }else{
                    //如果存在 就修改数量
                    commissionYes.setNum(commissionYes.getNum()+hands);
                    iCommissionYesService.updateNumById(commissionYes.getNum(),commissionYes.getId());
                }




                //打印卖出的股票来自哪

                for (SysBuy eligibleBuy : eligibleBuys) {
                    int buyHands = Math.min(Integer.parseInt(eligibleBuy.getHands()), hands);
                    System.out.println("卖出"+buyHands+"手,来自："+eligibleBuy.getName());
                    //根据symbol和buyPrice获取sysBuy 减去buyHands
                    SysBuy sysBuyByPrice = iSysBuyService.getSysBuyByPrice(eligibleBuy.getSymbol(), eligibleBuy.getBuyPrice());
                    sysBuyByPrice.setHands(String.valueOf(Integer.parseInt(sysBuyByPrice.getHands())-buyHands));
                    iSysBuyService.updateHandsByIds(sysBuyByPrice.getId(),sysBuyByPrice.getHands());
                    hands-=buyHands;
                    if(hands==0){
                        break;
                    }
                }
                //int min = Math.min(hands, remainingHands);
            }
            else{
                //要卖出的手数大于  大于等于卖出价格的总手数
                int sellhands=hands-remainingHands;
                //如果卖出时 大于卖出价买入的剩余手数小于要买入的手数
                CommissionYes commissionYes=iCommissionYesService.getCommissionBySymbolAndPriceSell(tbStockVoTest.getSymbol(),tbStockVoTest.getSellPrice(),myAccount.getId());
                if (commissionYes==null){
                    commissionYes=new CommissionYes();
                    commissionYes.setSymbol(tbStockVoTest.getSymbol());
                    commissionYes.setCommissionPrice(new BigDecimal(tbStockVoTest.getSellPrice()));
                    commissionYes.setNum(remainingHands);
                    commissionYes.setAccountId(myAccount.getId());
                    commissionYes.setState(2);
                    iCommissionYesService.add(commissionYes);
                }else{
                    //如果存在 就修改数量
                    commissionYes.setNum(commissionYes.getNum()+remainingHands);
                    iCommissionYesService.updateNumById(commissionYes.getNum(),commissionYes.getId());
                }







                for (SysBuy eligibleBuy : eligibleBuys) {
                    int min = Math.min(Integer.parseInt(eligibleBuy.getHands()), hands);
                    System.out.println("卖出"+min+"手,来自："+eligibleBuy.getName());
                    SysBuy sysBuyByPrice = iSysBuyService.getSysBuyByPrice(eligibleBuy.getSymbol(), eligibleBuy.getBuyPrice());
                    sysBuyByPrice.setHands(String.valueOf(Integer.parseInt(sysBuyByPrice.getHands())-min));
                    iSysBuyService.updateHandsByIds(sysBuyByPrice.getId(),sysBuyByPrice.getHands());
                    hands-=min;
                    if(hands==sellhands){
                        break;
                    }
                }
                if(sellhands>0){
                    System.err.println("还有"+sellhands+"未卖出");
                    SysSell sysSell=iSysSellService.selectSysSellBySymbolAndSellPrice(tbStockVoTest.getSymbol(),tbStockVoTest.getSellPrice());
                    if(sysSell==null){
                        sysSell=new SysSell();
                        sysSell.setName("卖"+UUID.randomUUID());
                        sysSell.setSellPrice(tbStockVoTest.getSellPrice());
                        sysSell.setSymbol(tbStockVoTest.getSymbol());
                        sysSell.setHands(String.valueOf(sellhands));
                        iSysSellService.add(sysSell);
                    }
                    else{
                        sysSell.setHands(String.valueOf(Integer.parseInt(sysSell.getHands())+sellhands));
                        iSysSellService.updateHandsByIds(sysSell.getId(),sysSell.getHands());
                    }
                    //将未撮合卖出的订单存入未完成委托表中
                    CommissionNo commissionNo=iCommissionNoService.getCommissionBySymbolAndPriceSll(tbStockVoTest.getSymbol(),tbStockVoTest.getSellPrice(),myAccount.getId());
                    if (commissionNo==null){
                        commissionNo=new CommissionNo();
                        commissionNo.setSymbol(tbStockVoTest.getSymbol());
                        commissionNo.setCommissionPrice(new BigDecimal(tbStockVoTest.getSellPrice()));
                        commissionNo.setNum(sellhands);
                        commissionNo.setAccountId(myAccount.getId());
                        commissionNo.setState(2);
                        iCommissionNoService.add(commissionNo);
                    }else{
                        //如果存在 就修改数量
                        commissionNo.setNum(commissionNo.getNum()+sellhands);
                        iCommissionNoService.updateNumById(commissionNo.getNum(),commissionNo.getId());
                    }




                }
            }
            return AjaxResult.success();
        }
        else{
            //小于我卖出的价格
            System.out.println("您卖出的价格为:"+tbStockVoTest.getSellPrice()+"暂无符合条件的买家");
            return AjaxResult.success();
        }

    }
    //查询所有的委托

    @GetMapping("entrustAllList")
    public AjaxResult entrustAllList()
    {
        Long userId = SecurityUtils.getUserId();
        List<Commission> listAll=iCommissionService.entrustAllList(userId);
        return AjaxResult.success(listAll);
    }

//  查询成功的委托
    @GetMapping("successEntrustList")
    public AjaxResult successEntrustList(){
        Long userId = SecurityUtils.getUserId();
        List<CommissionYes> list=iCommissionYesService.successEntrustList(userId);
        return AjaxResult.success(list);
    }


    @GetMapping("errorEntrustList")
    public AjaxResult errorEntrustList(){
        Long userId = SecurityUtils.getUserId();
        List<CommissionNo> list=iCommissionNoService.errorEntrustList(userId);
        return AjaxResult.success(list);
    }







}
